/* model */
import { ConnectorModuleComponentNameEnum } from '@src/modules/connector/model';
/* components */
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import {
  ConnectorModuleConnectorDialogDetailActionQuery,
} from '@src/modules/connector/components';
/* scss */
import '@src/modules/connector/view/setting/components/main/index.scss';
/* vue */
import {
  ComponentInstance,
  ComponentRenderProxy,
  computed,
  defineComponent,
  PropType,
  ref,
  Ref,
  reactive,
  watch,
  ComputedRef,
} from 'vue';
import { CommonComponentInstance } from '@model/VC';
import { CreateElement } from 'vue';

/* utils */
import _ from 'lodash';
import { connectorFromFieldsAddChildren, getConnectorOptionsFieldOptionValueByRuleForm, getRuleGroupFromFieldDisplayItem } from '@src/modules/connector/util';
import { getFixedValue } from '@src/modules/connector/util';
import { t } from '@src/locales'

type ActionQuery = {
  value: Array<any>;
  fromFieldList: Array<any>;
  toFieldList: Array<any>;
};
export type ConnectorSettingConfigPanelProps = {
  configData: any;
  type: string;
  fromApp: any;
  toApp: any;
  conditionalLimit: string;
};
enum ConnectorRuleSettingViewEmitEventNameEnum {
  RuleChange = 'ruleChange',
}

const operatorTypes: any = {
  // 相等
  EQ: t('common.base.equal'),
  NOT_EQ: t('common.base.notEqual'),
  // 介于 在...之间
  BETWEEN: t('common.base.between'),
  // 包含
  CONTAINS: t('common.base.include'),
  NOT_CONTAINS: t('common.base.exclude'),
  NOT_BETWEEN: t('common.base.notBetween'),
  MORE: t('common.base.greaterThan'),
  LESS: t('common.base.lessThan'),
  EMPTY: t('common.connector.empty'),
  EARLY: t('common.base.earlyThan'),
  LATE: t('common.base.lateThan'),
  LOCATED: t('common.base.located'),
  NOT_LOCATED: t('common.base.notLocated')
};

export default defineComponent({
  props: {
    configData: {
      type: Object as PropType<ActionQuery>,
      default: () => ({
        selectRuleForms: [],
        fromFieldList: [],
        toFieldList: [],
        conditionalLimit: '1'
      }),
    },
    fromApp: {
      type: Object,
      default: ()=>({}),
    },
    toApp: {
      type: Object,
      default: ()=>({}),
    },
  },
  components: {
    NoDataViewNew,
    ConnectorModuleConnectorDialogDetailActionQuery,
  },
  emits: [],
  setup(props: ConnectorSettingConfigPanelProps, { slots, emit }) {
    const showModal = ref(false);

    const modalRule: Ref<any> = ref({
      selectRuleForms: [],
      fromFieldList: [],
      toFieldList: [],
      conditionalLimit: '1'
    });

    /**
     * @description: 打开弹窗
     * @return {*}
     */
    const openModal = () => {
      initModalRule();
      showModal.value = true;
    };

    /**
     * @description: 初始化弹窗数据（查询、新建）
     * @return {*}
     */

    const initModalRule = () => {
      
      let newModalRule = _.cloneDeep(props.configData);
      
      // 添加子属性
      connectorFromFieldsAddChildren(newModalRule.fromFieldList);
      
      modalRule.value = newModalRule
      
    };

    /**
     * @description: 查询条件组变化
     * @return {*}
     */
    const onConnectorSelectRuleFormInputHandler = (val: any) => {
      
      let newValue: any = {
        ...props.configData,
        selectRuleForms: val,
      };
      
      // 添加子属性
      connectorFromFieldsAddChildren(newValue.fromFieldList);
      
      modalRule.value = newValue;
    };
    /** 选择表单未选择值时处理 */
    const onChangeCondition = (val: any) => {
      modalRule.value = { ...modalRule.value, conditionalLimit: val };
    };

    /**
     * @description: 已选择的条件组
     * @param {*} computed
     * @return {*}
     */
    const selectedSearchRuleList: ComputedRef<Array<any>> = computed(() => {
      return (props.configData?.selectRuleForms || [])
        .filter((item: any) => {
          return item.leftFieldValue;
        })
        .map((item: any) => {
          
          const fromFieldList = props.configData?.fromFieldList || [];
          
          // 添加子属性
          connectorFromFieldsAddChildren(fromFieldList);
          
          getRuleGroupFromFieldDisplayItem(item, fromFieldList);
          
          (props.configData?.toFieldList || []).forEach((field: any) => {
            if (item.leftFieldValue == field.enName) {
              item.field = field;
            }
          });
          
          return item;
          
        });
    });

    /**
     * @description: 规则变化
     * @return {*}
     */
    const onRuleInputHandler = (val: any) => {
      //@ts-ignore
      emit(ConnectorRuleSettingViewEmitEventNameEnum.RuleChange, val);
    };

    /**
     * @description: 弹窗确定
     * @return {*}
     */
    const submit = () => {
      onRuleInputHandler(modalRule.value);
      showModal.value = false;
    };
    return {
      showModal,
      onConnectorSelectRuleFormInputHandler,
      submit,
      openModal,
      modalRule,
      selectedSearchRuleList,
      onChangeCondition,
    };
  },
  render(h: CreateElement) {
    {
      /* start 设置弹窗 */
    }
    const modalAttr = {
      props: {
        show: this.showModal,
        title: t('common.connector.title.setDataSearchConditions'),
        bodyClass: 'connector-module-connector-dialog-detail form-connector-dialog',
        appendToBody: true,
        width: '840px'
      },
      on: {
        'update:show': (val: boolean) => {
          this.showModal = val;
        },
      },
    };

    const queryAttr = {
      directives: [
        {
          name: 'show',
          value: true,
        },
      ],
      props: {
        value: this.modalRule.selectRuleForms,
        toFieldList: this.modalRule.toFieldList,
        fromFieldList: this.modalRule.fromFieldList,
        fromBizTypeName: this.fromApp.name || '',
        toBizTypeName: this.toApp.name || '',
        maxLength: 10,
        conditionalLimit: this.modalRule.conditionalLimit || '1',
        isShowCondition: true,
      },
      on: {
        input: this.onConnectorSelectRuleFormInputHandler,
        changeCondition: this.onChangeCondition,
      },
    };

    const configModal = () => {
      return (
        <base-modal {...modalAttr}>
          {/* <p className="modal-config-desc">
            满足一个条件组内所有条件或满足不同条件组中其中一个条件组内所有条件，可以进入这条连接线下的节点。
          </p> */}
          {(
            <ConnectorModuleConnectorDialogDetailActionQuery {...queryAttr} />
          )}

          <div slot="footer" style="text-align:right;">
            <el-button onClick={() => (this.showModal = false)}>
              {t('common.base.cancel')}
            </el-button>
            <el-button type="primary" onClick={() => this.submit()}>
              {t('common.base.makeSure')}
            </el-button>
          </div>
        </base-modal>
      );
    };

    return (
      <div class="config-panel-setting">
        { (
          <div>
            <el-button class="form-connector-setting-select-btn" type="primary" plain onClick={() => this.openModal()}>
              {t('common.connector.setFilterCondition')}
            </el-button>
            {this.selectedSearchRuleList.length > 0 ? (
              <div class="config-panel-setting-detail">
                <div class="setting-title">{t('common.connector.conditionGroup')}</div>
                <div class="setting-content">
                  {this.selectedSearchRuleList.length > 0 ? (
                    this.selectedSearchRuleList.map((item, index) => {
                      return (
                        <div class="rule-text">
                          <span class="and-text">
                            {index == 0 ? t('common.connector.text.when') : t('common.connector.text.and')}&nbsp;
                          </span>
                          <span>
                            {item.field?.cnName || item.field?.displayName}
                          </span>
                          <span class="operator-text">
                            &nbsp;{operatorTypes[item.operator]}&nbsp;
                          </span>
                          {item?.condition != 'fixedValue' ? (
                            <span>{item.rightField?.cnName}</span>
                          ) : (
                            <span>{getFixedValue(item)}</span>
                          )}
                        </div>
                      );
                    })
                  ) : (
                    <no-data-view-new />
                  )}
                </div>
              </div>
            ) : (
              ''
            )}
          </div>
        ) }

        {configModal()}
      </div>
    );
  },
});
